package com.xiaohui.user.delayQueue;


import com.xiaohui.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.Set;

@Service
@Slf4j
public class TaskService {

    @Resource
    private RedisUtil redisUtil;

    private static final String TASK_KEY = "task";

    public void pushTask(Task task) {
        if (task == null) {
            return;
        }
        if (task.getStartTime().compareTo(new Date()) <= 0) {
            return;
        }

        log.info("添加任务到延迟队列");

        redisUtil.zAdd(TASK_KEY, task.getTaskId(), task.getStartTime().getTime());
    }


    public Set<String> pullTask() {

        log.info("从延迟队列中获取任务");
        Set<String> taskIds = redisUtil.rangeByScore(TASK_KEY, 0, System.currentTimeMillis());
        if (CollectionUtils.isEmpty(taskIds)) {
            return Collections.emptySet();
        }

        // 删除任务
        redisUtil.removeZsetList(TASK_KEY, taskIds);

        // 返回任务
        return taskIds;
    }

}
